<template>
  <div class="footer">
    <span class="name"> {{ audioMes.name ? audioMes.name : "请选择歌曲" }}</span>
    <audio :src="audioMes.songUrl" ref="audio" autoplay>歌曲</audio>
    <img :src="audioMes.picUrl" id="pic" @click="showDialog" ref="pic" />

    <div class="slider-demo-block">
      <el-slider v-model="progress" :show-tooltip="false" @input="changeProgress" />
    </div>
    <div class="timeRecord">
      <span style="color: white">{{ curTime }}/{{ durTime }}</span>
    </div>

    <el-icon @click="pre" id="preBtn"><CaretLeft /></el-icon>
    <el-icon @click="play" class="playBtn" v-show="flag === 0"><VideoPlay /></el-icon>
    <el-icon @click="play" class="playBtn" v-show="flag === 1"><VideoPause /></el-icon>
    <el-icon @click="next" id="nextBtn"><CaretRight /></el-icon>

    <!-- 播放模式键 -->

    <img
      src="@/static/img/circleOne.svg"
      alt=""
      v-show="playStyle === 0"
      class="playStyle"
      @click="changePlayStyle"
    />
    <img
      src="@/static/img/circle.svg"
      alt=""
      v-show="playStyle === 1"
      class="playStyle"
      @click="changePlayStyle"
    />
    <img
      src="@/static/img/random.svg"
      alt=""
      v-show="playStyle === 2"
      class="playStyle"
      @click="changePlayStyle"
    />

    <el-dropdown @command="handleCommand" class="songButtom">
      <span>
        <img src="@/static/img/songPlayList.svg" class="songPlayListIcon" />
      </span>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item v-for="(item, index) in songPlayList" :command="item">
            <p
              :style="{
                color: index == songPlayNowLable ? 'red' : 'black',
              }"
            >
              {{ item.name }}
            </p>
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>

    <el-dropdown @command="clear" class="clearButtom">
      <span>
        <img
          style="width:30px;height:30px:position:absolut;right:0;  cursor: pointer;"
          src="@/static/img/clear.svg"
        />
      </span>

      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item> 清空歌单 </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>

    <!-- 歌词框 -->
    <el-dialog v-model="visible" :show-close="true" width="1000px" :modal="true">
      <body class="dia_body">
        <img :src="audioMes.picUrl" id="dia_pic" />
        <p class="songName">{{ audioMes.name ? audioMes.name : "wait" }}</p>
        <p class="singerName"></p>
        <el-button class="commentBtn" @click="openComment">打开评论</el-button>
        <div class="lyricDiv" ref="lyricDiv">
          <div class="allLyric">
            <p
              class="lyric-row"
              ref="sentence_dom"
              v-for="(item, index) in lyricTxt"
              :key="index"
              :style="{
                'font-size': index == lyricCur - 1 ? '1.3rem' : '.9rem',
                color: index == lyricCur - 1 ? 'red' : 'black',
              }"
            >
              {{ item.text }}
            </p>
          </div>
        </div>
        <div class="headerSlider">
          <el-slider v-model="progress" :show-tooltip="false" @input="changeProgress" />
        </div>
      </body>
    </el-dialog>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, toRefs, watch } from "vue";
import { storeToRefs } from "pinia";
import { getLyric } from "@/service/songs";
import { storage } from "@/stores/storage";
import { getSongtime } from "@/utils/practicalFun";

export default defineComponent({
  setup() {
    let store = storage();
    let audio = ref();
    let progress = ref(0);
    let lyricTxt = ref([]);
    let lyricDiv = ref(null);
    let flag = ref(0);
    let lyricCur = ref(0);
    let lyricBook = [];
    let sentence_dom = ref();
    let durTime = ref(0);
    let playStyle = ref(0); //0,单曲循环，1循环播放，2随机播放
    let songPlayNowLable = ref(0);
    let pic = ref(null);
    const visible = ref(false);
    const { songPlayList, audioMes, isImmediatelyPlay, isPlayAll } = storeToRefs(store);
    async function initial_lyric() {
      await getLyric(audioMes.value.id)
        .then((res) => {
          if (res.status === 200) {
            let data = res.data.lrc.lyric;
            lyricTxt.value = formatLyric(data);
          }
        })
        .catch((res) => {
          if (res) {
            ElMessage("歌词获取有误");
          }
        });
      audio.value.ontimeupdate = lyricF;
      for (let i = 0; i < lyricTxt.value.length; i++) {
        lyricBook[i] = 0;
      }
      lyricCur.value = 0;
    }
    //歌单点击的必经点 handleCommand
    const handleCommand = (item) => {
      for (let i = 0; i < songPlayList.value.length; i++) {
        if (item.id === songPlayList.value[i].id) songPlayNowLable.value = i;
      }
      flag.value = 0;
      if (isPlayAll.value === false) {
        ElMessage(`当前播放 ${item.name}`);
      }

      store.setAudioMes(item.id, item.name, item.songUrl, item.picUrl);

      initial_lyric();

      play();
    };
    function clear() {
      store.clearSongPlayList();
    }
    function getSongPlayListIndex(objArr, obj) {
      for (let i = 0; i < objArr.length; i++) {
        if (obj.id === objArr[i].id) {
          return i;
        }
      }
    }

    function getRandInteger(min, max, disableId) {
      let id = Math.floor(Math.random() * (max - min + 1)) + min;
      if (id === disableId) {
        return getRandInteger(min, max, disableId);
      } else {
        return id;
      }
    }
    // direction 0左1右
    function nextOne(direction) {
      let index = null;
      if (playStyle.value === 0) {
        index = getSongPlayListIndex(songPlayList.value, audioMes.value);
      } else if (playStyle.value === 1) {
        if (direction === 0) {
          index =
            (getSongPlayListIndex(songPlayList.value, audioMes.value) -
              1 +
              songPlayList.value.length) %
            songPlayList.value.length;
        } else if (direction === 1) {
          index =
            (getSongPlayListIndex(songPlayList.value, audioMes.value) + 1) %
            songPlayList.value.length;
        }
      } else if (playStyle.value === 2) {
        index = getRandInteger(
          0,
          songPlayList.value.length,
          getSongPlayListIndex(songPlayList.value, audioMes.value)
        );
      }
      handleCommand(songPlayList.value[index]);
    }
    function play() {
      if (audio.value.currentTime === audio.value.duration) {
        initial_lyric();
      }
      if (flag.value == 0) {
        audio.value.play();
        pic.value.style.animationPlayState = "running";
        flag.value = 1;
      } else {
        pic.value.style.animationPlayState = "paused";
        audio.value.pause();
        flag.value = 0;
      }
    }
    function pre() {
      nextOne(0);
    }
    function next() {
      nextOne(1);
    }

    function changeProgress() {
      audio.value.currentTime = (progress.value / 100) * audio.value.duration;
      for (let i = 0; i < lyricTxt.value.length; i++) {
        if (audio.value.currentTime < lyricTxt.value[i].time) {
          lyricCur.value = i;
          break;
        }
      }
      for (let i = 0; i < lyricCur.value; i++) {
        lyricBook[i] = 1;
      }
      for (let i = lyricCur.value; i < lyricTxt.value.length; i++) {
        lyricBook[i] = 0;
      }
    }
    let curTime = ref(0);

    function lyricF(e) {
      let { duration, currentTime } = e.target;
      curTime.value = getSongtime(currentTime * 1000);
      durTime.value = getSongtime(duration * 1000);
      progress.value = (currentTime / duration) * 100;
      if (
        lyricTxt.value.length > lyricCur.value &&
        currentTime >= lyricTxt.value[lyricCur.value].time &&
        lyricBook[lyricCur.value] === 0
      ) {
        lyricBook[lyricCur.value] = 1;
        lyricCur.value++;
      }

      if (lyricDiv.value) {
        lyricDiv.value.scrollTop = 40 * lyricCur.value - 120;
      }
      if (currentTime / duration == 1) {
        flag.value = 0;
        nextOne(1);
      }
    }
    //传入初始歌词文本text
    function formatLyric(text) {
      let result = [];
      let arr = text.split("\n"); //原歌词文本已经换好行了方便很多，我们直接通过换行符“\n”进行切割
      let row = arr.length; //获取歌词行数
      for (let i = 0; i < row; i++) {
        let temp_row = arr[i]; //现在每一行格式大概就是这样"[00:04.302][02:10.00]hello world";
        let temp_arr = temp_row.split("]"); //我们可以通过“]”对时间和文本进行分离
        let text = temp_arr.pop(); //把歌词文本从数组中剔除出来，获取到歌词文本了！
        //再对剩下的歌词时间进行处理
        temp_arr.forEach((element) => {
          let obj = {};
          let time_arr = element.substr(1, element.length - 1).split(":"); //先把多余的“[”去掉，再分离出分、秒
          let s = parseInt(time_arr[0]) * 60 + Math.ceil(time_arr[1]); //把时间转换成与currentTime相同的类型，方便待会实现滚动效果
          obj.time = s;
          obj.text = text;
          result.push(obj); //每一行歌词对象存到组件的lyric歌词属性里
        });
      }
      result.sort(sortRule); //由于不同时间的相同歌词我们给排到一起了，所以这里要以时间顺序重新排列一下
      // this.$store.commit("setLyric", this.lyric); //把歌词提交到store里，为了重新进入该组件时还能再次渲染
      // return result.filter(function(item,index,self){
      //     return item.text!==""
      // })
      return result;
    }
    function sortRule(a, b) {
      //设置一下排序规则
      return a.time - b.time;
    }
    function changePlayStyle() {
      playStyle.value = (playStyle.value + 1) % 3;
    }
    function showDialog() {
      if (audioMes.value.id) {
        visible.value = !visible.value;
      }
    }
    function openComment() {
      store.setCommentId(audioMes.value.id);
      store.setCommentsType(0);
      store.changeIsShowComment();
    }
    watch(
      () => isImmediatelyPlay.value,
      (v1, v2) => {
        if (v1 === true) {
          handleCommand(songPlayList.value[songPlayList.value.length - 1]);
          store.changeIsImmediatelyPlay();
        }
      },
      { deep: true, immediate: true }
    );

    return {
      songPlayList,
      audio,
      audioMes,
      visible,
      lyricTxt,
      lyricDiv,
      lyricCur,
      play,
      pre,
      next,
      handleCommand,
      showDialog,
      openComment,
      changeProgress,
      changePlayStyle,
      playStyle,
      progress,
      isImmediatelyPlay,
      flag,
      curTime,
      sentence_dom,
      durTime,
      songPlayNowLable,
      clear,
      pic,
    };
  },
});
</script>

<style scoped>
.songButtom {
  width: 20px;
  height: 20px;
  position: absolute;
  bottom: 30px;
  right: 50px;
}
.clearButtom {
  position: absolute;
  bottom: 0px;
  right: 0;
}

.playBtn {
  position: absolute;
  left: 450px;
  bottom: 0;
  font-size: 40px;
  color: white;
}
.playBtn:hover {
  cursor: pointer;
  color: #409eff;
}
#preBtn {
  position: absolute;
  left: 350px;
  bottom: 0;
  font-size: 40px;
  color: white;
}
#preBtn:hover {
  cursor: pointer;
  color: #409eff;
}
#nextBtn {
  position: absolute;
  left: 550px;
  bottom: 0;
  font-size: 40px;
  color: white;
}
#nextBtn:hover {
  cursor: pointer;
  color: #409eff;
}
#pic {
  border-radius: 50%;
  width: 60px;
  height: 60px;
  position: absolute;
  left: 50px;
  animation: spin_circle 6s linear infinite;
}
#pic:hover {
  cursor: pointer;
}

/* 歌曲name */
.name {
  position: absolute;
  bottom: 20px;
  left: 120px;
  color: white;
}
.dia_header {
  height: 3px;
  width: 950px;
  background-color: purple;
}

.dia_body {
  position: relative;
  height: 400px;
  width: 950px;
  background-color: white;
}

#dia_pic {
  position: absolute;
  width: 200px;
  height: 200px;
  top: 90px;
  left: 60px;
}
.songName {
  width: 50%;
  text-align: center;

  font-size: 30px;
  position: absolute;
  top: 30px;
  left: 370px;
  color: white;
  color: black;
}
.lyricDiv {
  font-size: 20px;
  position: relative;

  top: 100px;
  left: 285px;
  width: 68%;
  height: 250px;
  color: white;
  overflow: auto;
  scrollbar-width: none;
}

.lyric-row {
  width: 100%;

  height: 40px;
  line-height: 40px;
  transition: 0.5s;
  text-align: center;
}
.allLyric {
  position: absolute;
  width: 100%;
  background-color: #fff;
}
.commentBtn {
  position: absolute;
  top: 300px;
  left: 100px;
}

.slider-demo-block {
  display: flex;
  align-items: center;
  width: 522px;
  position: relative;
  top: -5px;
  left: 190px;
}
.timeRecord {
  position: relative;
  bottom: 30px;
  left: 730px;
}
.headerSlider {
  width: 500px;
  position: absolute;
  left: 350px;
  bottom: 0;
}
.playStyle {
  transform: scale(0.1);
  color: white;
  position: absolute;
  left: 550px;
  top: -60px;
}
.playStyle:hover {
  cursor: pointer;
}
.songPlayListIcon {
  width: 40px;
  height: 40px;
  position: absolute;
  bottom: -25px;
  right: 0px;
  cursor: pointer;
}
@keyframes spin_circle {
  0% {
    transform: rotate(0);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
